<?

class phpNMS {
	private $rootPath = '';
	private $cfg;
	public $db;
	public $template = 'home';
	public $tab = 'summary';
	public $page = '';
	public $timerEvents = array();
	public function __construct($cfg=array()) {
		$this->rootPath = realpath(dirname(__FILE__).'/../').'/';
		$this->cfg = new classConfig($this->rootPath.'config/config.ini');
		$this->session = new classSession($this->cfg->Session);
		$this->events = new classEventLog($this);
		foreach ($this->cfg AS $name=>$value) {
			switch ($name) {
				case 'Database':
					$this->db = new classMySQLi($value);
					break;
			
			}
		
		
		
		}
	} 
	public function setPageVariables($params=array()) {
		if (isset($params['template'])) {
			$this->template = $params['template'];
		}
		foreach ($params AS $name=>$value) {
			switch ($name) {
				case 'tab':
				case 'page':
					$_SESSION[$this->template][$name] = $value;
					break;
			}
		}
	}
	public function getTemplate() { return $this->template;}
	public function getTemplatePath($type='html') { return $this->rootPath.'templates/'.$this->template.'_'.$type.'.php';}
	public function getPageRefeshTime() {
		$temp = $this->template;
		if (isset($this->cfg->Refresh->$temp)) {
			return $this->cfg->Refresh->$temp;
		} else return false;
	}
	public function getSubTab($type='')  { 
		if (isset($_SESSION[$this->template]['tab'])) {
			if (!empty($type)) {
				return $type.'_'.$_SESSION[$this->template]['tab'];
			} else {
				return $_SESSION[$this->template]['tab'];
			}
		} else {
			return '';
		}
	}
	
	public function getPage()  { 
		if (isset($_SESSION[$this->template]['page'])) {
			return $_SESSION[$this->template]['page'];
		} else {
			return '';
		}
	}
	public function getSubTabPath($type='') { 
		if (isset($_SESSION[$this->template]['page']) && !empty($_SESSION[$this->template]['page'])) {
			return 'tabs/'.$_SESSION[$this->template]['page'].'_html.php';
		} elseif (!empty($type) && is_file($this->rootPath.'templates/tabs/'.$type.'_'.$_SESSION[$this->template]['tab'].'_html.php')) {
			return 'tabs/'.$type.'_'.$_SESSION[$this->template]['tab'].'_html.php';
		} else if (isset($_SESSION[$this->template]['tab']) && !empty($_SESSION[$this->template]['tab'])) {
			return 'tabs/'.$_SESSION[$this->template]['tab'].'_html.php';		
		} else {
			return 'tabs/summary_html.php';		
		}
	
	}
	public function getBodyClasses() {
		return $this->template;
	
	}
	
	public function getDeviceTypes() {
		$sql = "SELECT type,description FROM device_types ORDER BY sort_order ASC;";
		return $this->db->getObjects($sql);
	}
	public function getDevices($params=array()) {
		$output = array();
		$where = array();
		
		foreach ($params AS $name=>$value) {
			switch ($name) {
				case 'status':
					$where[] = "status='".$this->db->escape($value)."'";
					break;
				case 'disabled':
					$where[] = "disabled=".(int)$value;
					break;
				case 'type':
					if (!empty($value)) {
						$where[] = "type='".$this->db->escape($value)."'";
					}
					break;			
			}
		}
		$sql = 	"SELECT *,UNIX_TIMESTAMP(last_discovery) AS last_discovery,UNIX_TIMESTAMP(last_poll) AS last_poll ".
				"FROM devices ";
		if (!empty($where)) {
			$sql .= "WHERE ".implode(' AND ',$where)." ";
		}
		$sql .=	"ORDER BY description ASC;";
		$this->timerEvent('Start SQL Query');
		$devices = $this->db->getObjects($sql);
		$this->timerEvent('End SQL Query');
		foreach ($devices AS $fields) {
			$output[] = new objDevice($fields);		
		}
		return $output;
	
	}
	
	
	public function getPath($folder='') {
		foreach ($this->cfg->Paths AS $key=>$path) {
			if ($key == $folder) {
				return $this->rootPath.$path;			
			}		
		}
		return $this->rootPath.'cache/';
	}
	public function determineOS($sysDescr='') {
		$output = '';
		foreach ($this->cfg->OS AS $name=>$value) {
			if (empty($output)) {
				$class = $this->buildClassName('os_'.$name);
				if (class_exists($class,true)) {
					echo $class.chr(10);
					$os = new $class();
					if (method_exists($os,'checkDescription')) {
						$output = $os->checkDescription($sysDescr);
					}
				}
			}
		}
		echo 'OS Detected: '.$output.chr(10);
		return empty($output)?'generic':$output;
	}
	
	
	public function formatBytes($bytes, $precision = 2) { 
 	   $units = array('B', 'KB', 'MB', 'GB', 'TB'); 
   
    	$bytes = max($bytes, 0); 
	    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    	$pow = min($pow, count($units) - 1); 
   
	    $bytes /= pow(1024, $pow); 
   
    	return round($bytes, $precision) . ' ' . $units[$pow]; 
	}
	
	public function format_uptime($seconds) {
	  $secs = intval($seconds % 60);
	  $mins = intval($seconds / 60 % 60);
	  $hours = intval($seconds / 3600 % 24);
	  $days = intval($seconds / 86400);
	  
	  if ($days > 0) {
	    $uptimeString .= $days;
	    $uptimeString .= (($days == 1) ? " day" : " days");
	  }
	  if ($hours > 0) {
	    $uptimeString .= (($days > 0) ? ", " : "") . $hours;
	    $uptimeString .= (($hours == 1) ? " hr" : " hrs");
	  }
	  if ($mins > 0) {
	    $uptimeString .= (($days > 0 || $hours > 0) ? ", " : "") . $mins;
	    $uptimeString .= (($mins == 1) ? " min" : " mins");
	  }
	  /*
	  if ($secs > 0) {
	    $uptimeString .= (($days > 0 || $hours > 0 || $mins > 0) ? ", " : "") . $secs;
	    $uptimeString .= (($secs == 1) ? " sec" : " secs");
	  }*/
	  return $uptimeString;
	}
	
	public function buildClassName($string ='') {
		$className = '';
		$parts = explode('_',$string);
		$className = $parts[0];
		unset($parts[0]);
		foreach ($parts AS $part) {
			$className .= ucfirst($part);		
		}
		return $className;
	}
	
	public function getVersion() { return $this->cfg->Application->version;}
	public function timerEvent($msg) {
		$parts = explode(' ',microtime());
		$time = $parts[1].substr($parts[0],1);
		$this->timerEvents[$time] = $msg;
	}
	public function timerReport() {
		$start = 0;
		$last = 0;
		$total = 0;
		echo '<table id="timerReport">';
		echo '<thead><tr><th>Time (s)</th><th>Event</th><th>Total</th></tr></thead>';
		echo '<tbody>';
		foreach ($this->timerEvents AS $time=>$event) {
			if ($start==0) {
				$last = $start=$time;
			}
			$diff = $time-$last;
			echo '<tr><td>'.round($diff,3).'</td><td> '.$event.'</td><td>'.round($total,3).'</td></tr>';		
			$last = $time;
			$total += $diff;
		}
		echo '</tbody>';
		echo '<tfoot>';
		echo '<tr><td colspan="2">Total Execution Time</td><td>'.round($total,3).'</td></tr>';
		echo '</tfoot>';
		echo '</table>';
		
//		echo '<pre>'.print_r($this->timerEvents,1).'</pre>';
	}
}
?>